차이를 제거하기
리팩토링을 하는 과정에서 얼추 중복된 코드를 제거하기 위해 임시로 두 코드를 완전히 중복된 코드로 만드는 패턴.
설명
How do you unify two similar looking pieces of code? Gradually bring them closer. Unify them only when they are absolutely identical. …
This refactoring occurs at all levels of scale:
- Two loop structures are similar. By making them identical, you can merge them.
- Two branches of a conditional are similar. By making them identical, you can eliminate the conditional.
- Two methods are similar. By making them identical, you can eliminate one.
- Two classes are similar. By making them identical, you can eliminate one.
Sometimes you need to approach reconciling differences backward—that is, think about how the last step of the change could be trivial, then work backward. For example, if you want to remove several subclasses, the trivial last step is if a subclass contains nothing. Then the superclass can replace the subclass without changing the behavior of the system. To empty out this subclass, this method needs to be made identical to the one in the superclass. One by one, empty out the subclasses and, when they are empty, replace references to them with references to the superclass.
—Chapter 31, Test-driven development: by example
사례
Franc.equals()
is almost the same asMoney.equals()
. If we make them precisely the same, then we can delete the implementation inFranc
without changing the meaning of the program. —Chapter 6, Test-driven development: by example